//
//  EventEditViewController.m
//  lvtu
//
//  Created by martin on 12-9-1.
//
//

#import "EventEditViewController.h"
#import "CustomTabBarController.h"
#import "DataSource.h"
#import "ShowDesiginViewController.h"

@interface EventEditViewController ()

@end

@implementation EventEditViewController
@synthesize delegate;
@synthesize isChanged;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (id)init
{
    self = [super init];
    if (self) {
        
        backgroundScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
        backgroundScrollView.backgroundColor = [UIColor clearColor];
        backgroundScrollView.contentSize = CGSizeMake(self.view.frame.size.width, self.view.frame.size.height);
        backgroundScrollView.pagingEnabled = NO;
        backgroundScrollView.scrollEnabled = NO;
        backgroundScrollView.clipsToBounds = YES;
        backgroundScrollView.scrollsToTop = YES;
        backgroundScrollView.showsVerticalScrollIndicator = NO;
        backgroundScrollView.showsHorizontalScrollIndicator = NO;
        backgroundScrollView.delegate = self;
        [self.view addSubview:backgroundScrollView];
        
        currentDateLabel = [[UILabel alloc] initWithFrame:CGRectMake(90, 15, 50, 20)];
        currentDateLabel.font = [UIFont boldSystemFontOfSize:15];
        currentDateLabel.backgroundColor = [UIColor clearColor];
        currentDateLabel.textColor = [UIColor colorWithRed:252/255.0 green:100/255.0 blue:22/255.0 alpha:1.0];
        currentDateLabel.textAlignment = UITextAlignmentLeft;
        [backgroundScrollView addSubview:currentDateLabel];
        
        totleDateLabel = [[UILabel alloc] initWithFrame:CGRectMake(135, 16, 160, 20)];
        totleDateLabel.font = [UIFont boldSystemFontOfSize:14];
        totleDateLabel.backgroundColor = [UIColor clearColor];
        totleDateLabel.textColor = [UIColor colorWithRed:122/255.0 green:143/255.0 blue:68/255.0 alpha:1];
        totleDateLabel.textAlignment = UITextAlignmentLeft;
        [backgroundScrollView addSubview:totleDateLabel];
        
        citySelectLabel = [[UILabel alloc] initWithFrame:CGRectMake(44, 48, 200, 12)];
        citySelectLabel.font = [UIFont systemFontOfSize:10];
        citySelectLabel.backgroundColor = [UIColor clearColor];
        citySelectLabel.textColor = [UIColor colorWithRed:122/255.0 green:143/255.0 blue:68/255.0 alpha:1];
        citySelectLabel.textAlignment = UITextAlignmentLeft;
        citySelectLabel.text = @"选择此时间段所在的城市或地点：";
        [backgroundScrollView addSubview:citySelectLabel];
        
        citySelectView = [[CitySelectView alloc] initWithFrame:CGRectMake(30, 60, 260, 50)];
        citySelectView.index = 5000;
        citySelectView.delegate = self;
        [backgroundScrollView addSubview:citySelectView];
        
        eventAddLabel = [[UILabel alloc] initWithFrame:CGRectMake(44, 120, 200, 12)];
        eventAddLabel.font = [UIFont systemFontOfSize:10];
        eventAddLabel.backgroundColor = [UIColor clearColor];
        eventAddLabel.textColor = [UIColor colorWithRed:122/255.0 green:143/255.0 blue:68/255.0 alpha:1];
        eventAddLabel.textAlignment = UITextAlignmentLeft;
        eventAddLabel.text = @"添加事件：";
        [backgroundScrollView addSubview:eventAddLabel];
        
        tripSelectButton = [[EventAddView alloc] initWithFrame:CGRectMake(44, 130, 44, 56) Type:EVENTTYPE_TRAVEL];
        tripSelectButton.delegate = self;
        [backgroundScrollView addSubview:tripSelectButton];
        
        eatSelectButton = [[EventAddView alloc] initWithFrame:CGRectMake(93, 130, 44, 56) Type:EVENTTYPE_EAT];
        eatSelectButton.delegate = self;
        [backgroundScrollView addSubview:eatSelectButton];
        
        liveSelectButton = [[EventAddView alloc] initWithFrame:CGRectMake(142, 130, 44, 56) Type:EVENTTYPE_LIVE];
        liveSelectButton.delegate = self;
        [backgroundScrollView addSubview:liveSelectButton];
        
        buySelectButton = [[EventAddView alloc] initWithFrame:CGRectMake(191, 130, 44, 56) Type:EVENTTYPE_BUY];
        buySelectButton.delegate = self;
        [backgroundScrollView addSubview:buySelectButton];
        
        playSelectButton = [[EventAddView alloc] initWithFrame:CGRectMake(240, 130, 44, 56) Type:EVENTTYPE_PLAY];
        playSelectButton.delegate = self;
        [backgroundScrollView addSubview:playSelectButton];
        
        UIImage *guideImage = [[UIImage alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"bg_texttianjia.png" ofType:nil]];
        defaultGuideView = [[UIImageView alloc] initWithImage:guideImage];
        [guideImage release];
        [defaultGuideView setFrame:CGRectMake(74, 210, 175, 25)];
        [backgroundScrollView addSubview:defaultGuideView];
        
        preButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 155, 26, 50)];
        [preButton setImage:[UIImage imageNamed:@"btn_prev_normal.png"] forState:UIControlStateNormal];
        [preButton setImage:[UIImage imageNamed:@"btn_prev_press.png"] forState:UIControlStateHighlighted];
        [preButton addTarget:self action:@selector(preDayPressed) forControlEvents:UIControlEventTouchUpInside];
        
        nextButton = [[UIButton alloc] initWithFrame:CGRectMake(294, 155, 26, 50)];
        [nextButton setImage:[UIImage imageNamed:@"btn_next_normal.png"] forState:UIControlStateNormal];
        [nextButton setImage:[UIImage imageNamed:@"btn_next_press.png"] forState:UIControlStateHighlighted];
        [nextButton addTarget:self action:@selector(nextDayPressed) forControlEvents:UIControlEventTouchUpInside];
        [backgroundScrollView addSubview:nextButton];
        
        eventShowLabel = [[UILabel alloc] initWithFrame:CGRectMake(44, 190, 200, 12)];
        eventShowLabel.font = [UIFont systemFontOfSize:10];
        eventShowLabel.backgroundColor = [UIColor clearColor];
        eventShowLabel.textColor = [UIColor colorWithRed:122/255.0 green:143/255.0 blue:68/255.0 alpha:1];
        eventShowLabel.textAlignment = UITextAlignmentLeft;
        eventShowLabel.text = @"已添加事件：";
        [backgroundScrollView addSubview:eventShowLabel];
        
        UIImage *eventShowViewBgImage = [[UIImage alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"bg_whiteframe.png" ofType:nil]];
        eventShowBgView = [[UIImageView alloc] initWithImage:[eventShowViewBgImage stretchableImageWithLeftCapWidth:30 topCapHeight:10]];
        eventShowBgView.userInteractionEnabled = YES;
        [eventShowViewBgImage release];
        [eventShowBgView setFrame:CGRectMake(30, 205, 260, 110)];
        [backgroundScrollView addSubview:eventShowBgView];
        
        eventShowView = [[UIScrollView alloc] initWithFrame:CGRectMake(10, 10, 240, 90)];
        eventShowView.backgroundColor = [UIColor clearColor];
        eventShowView.contentSize = CGSizeMake(240, 100);
        eventShowView.pagingEnabled = NO;
        eventShowView.scrollEnabled = YES;
        eventShowView.clipsToBounds = YES;
        eventShowView.scrollsToTop = YES;
        eventShowView.showsVerticalScrollIndicator = YES;
        eventShowView.showsHorizontalScrollIndicator = NO;
        eventShowView.delegate = self;
        [eventShowBgView addSubview:eventShowView];
        
        isChanged = NO;
    }
    return self;
}

- (void)dealloc
{
    [currentDateLabel release];currentDateLabel = nil;
    [totleDateLabel release];totleDateLabel = nil;
    [citySelectLabel release];citySelectLabel = nil;
    [citySelectView release];citySelectView = nil;
    [eventAddLabel release];eventAddLabel = nil;
    [tripSelectButton release];tripSelectButton = nil;
    [eatSelectButton release];eatSelectButton = nil;
    [liveSelectButton release];liveSelectButton = nil;
    [buySelectButton release];buySelectButton = nil;
    [playSelectButton release];playSelectButton = nil;
    [defaultGuideView release];defaultGuideView = nil;
    [preButton release];preButton = nil;
    [nextButton release];nextButton = nil;
    [super dealloc];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    NSLog(@"%d",self.tabBarController.selectedIndex);
	// Do any additional setup after loading the view.
    UILabel* tempLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 44)];
    [tempLabel setText:@"旅途设计"];
    [tempLabel setBackgroundColor:[UIColor clearColor]];
    [tempLabel setTextAlignment:UITextAlignmentCenter];
    [tempLabel setTextColor:[UIColor colorWithRed:111/255.0 green:117/255.0 blue:81/255.0 alpha:1.0]];
    [tempLabel setFont:[UIFont boldSystemFontOfSize:20]];
    self.navigationItem.titleView = tempLabel;
    [tempLabel release];
    tempLabel = nil;
    
    UIImage* leftImage = [UIImage imageNamed:@"btn_back_normal.png"];
    UIButton* leftbutton = [UIButton buttonWithType:UIButtonTypeCustom];
    leftbutton.frame = CGRectMake(0, 0, leftImage.size.width, leftImage.size.height);
    [leftbutton setBackgroundImage:leftImage forState:UIControlStateNormal];
    [leftbutton setBackgroundImage:[UIImage imageNamed:@"btn_back_press.png"] forState:UIControlStateHighlighted];
    [leftbutton addTarget:self action:@selector(backButtonPress:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* leftButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftbutton];
    self.navigationItem.leftBarButtonItem = leftButtonItem;
    [leftButtonItem release];
    
    UIImage* rightImage = [UIImage imageNamed:@"ButtonFinish_normal.png"];
    UIButton* rightbutton = [UIButton buttonWithType:UIButtonTypeCustom];
    rightbutton.frame = CGRectMake(0, 0, 51, 30);
    [rightbutton setBackgroundImage:rightImage forState:UIControlStateNormal];
    [rightbutton setBackgroundImage:[UIImage imageNamed:@"ButtonFinish_pressed.png"] forState:UIControlStateHighlighted];
    [rightbutton addTarget:self action:@selector(okButtonPress:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* rightButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightbutton];
    self.navigationItem.rightBarButtonItem = rightButtonItem;
    [rightButtonItem release];

    eventArray = [[NSMutableArray alloc] init];
    [eventArray addObjectsFromArray:[[DataSource shareInstance] getCurrentEvent]];
    [self reloadEventShowView];
}

- (void)viewDidUnload
{
    [eventShowBgView release];eventShowBgView = nil;
    [eventShowLabel release];eventShowLabel = nil;
    [eventShowView release];eventShowView = nil;
    [eventArray removeAllObjects];
    [eventArray release],eventArray = nil;
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return NO;
}

- (void)viewWillAppear:(BOOL)animated
{
    [citySelectView setCityInfo:[DataSource shareInstance].defaultCityInfo];
    if (eventShowView.hidden == NO) {
        [self reloadEventShowView];
    }
}

- (void)viewDidAppear:(BOOL)animated
{
    if (self.tabBarController.selectedIndex == 1) {
        [DataSource shareInstance].isEdit = YES;
    }
    else if (self.tabBarController.selectedIndex == 2)
    {
        [DataSource shareInstance].isEdit = NO;
    }
}

- (void)setCurrentInfo:(NSInteger) index
{
    currentDateLabel.text = [NSString stringWithFormat:@"第%d天",index];
    totleDateLabel.text = [NSString stringWithFormat:@"/ 共%d天 %@",[[DataSource shareInstance] getDateCount],[[DataSource shareInstance] getCurrentDate]];
    if (index != 1) {
        [backgroundScrollView addSubview:preButton];
    }
}

- (void)reloadEventShowView
{
    if ([eventArray count] != 0) {
        defaultGuideView.hidden = YES;
        eventShowLabel.hidden = NO;
        eventShowBgView.hidden = NO;
        eventShowView.hidden = NO;
        
        NSInteger height = [eventArray count]/3;
        if ([eventArray count]%3 > 0) {
            height ++;
            [backgroundScrollView setScrollEnabled:YES];
        }
        else
        {
            [backgroundScrollView setScrollEnabled:NO];
        }
        
        [backgroundScrollView setContentSize:CGSizeMake(self.view.frame.size.width, self.view.frame.size.height+90*height)];
        [eventShowBgView setFrame:CGRectMake(30, 205, 260, 20+90*height)];
        [eventShowView setFrame:CGRectMake(eventShowView.frame.origin.x, eventShowView.frame.origin.y, 240, 90*height)];
        
        int index = 0;
        for (PlaceInfo* info in eventArray) {
            EventThumbViem* view = [[EventThumbViem alloc] initWithFrame:CGRectMake((76+5)*(index%3)+2, index/3*90, 76, 90) Data:info];
            view.delegate = self;
            [view setViewType:YES];
            [eventShowView addSubview:view];
            [view release];
            index ++;
        }
    }
    else
    {
        [backgroundScrollView setContentSize:CGSizeMake(self.view.frame.size.width, self.view.frame.size.height)];
        [eventShowBgView setFrame:CGRectMake(30, 205, 260, 110)];
        [eventShowView setFrame:CGRectMake(10, 10, 240, 90)];
        [backgroundScrollView setScrollEnabled:NO];
        eventShowLabel.hidden = YES;
        eventShowBgView.hidden = YES;
        eventShowView.hidden = YES;
        defaultGuideView.hidden = NO;
    }
}

#pragma mark - button
- (void)backButtonPress:(id)sender
{
    if ([[DataSource shareInstance] getTotleEventCount] > 0 && ![DataSource shareInstance].isEdit) {
        UIAlertView* baseAlert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"返回时间选择画面，是否保存已经编辑的旅途。" delegate:self cancelButtonTitle:@"否" otherButtonTitles:@"是",nil];
        baseAlert.tag = 2000;
        [baseAlert show];
        [baseAlert release];
        return;
    }
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)okButtonPress:(id)sender
{
    if ([DataSource shareInstance].isEdit) {
        [self.navigationController popViewControllerAnimated:YES];
    }
    NSInteger eventCount = [[DataSource shareInstance] getTotleEventCount];
    if (eventCount > 0) {
        ShowDesiginViewController* showDesignViewController = [[ShowDesiginViewController alloc] init];
        [self.navigationController pushViewController:showDesignViewController animated:YES];
    }
    else {
        UIAlertView* baseAlert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"还没有编辑任何内容哟~" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [baseAlert show];
        [baseAlert release];
    }
}

- (void)preDayPressed
{
    [delegate touchPreDayButton];
}

- (void)nextDayPressed
{
    [delegate touchNextDayButton];
}

#pragma mark - imagebuttondelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1 && alertView.tag == 1000) {
        SelectCityViewController* selectCityViewController = [[SelectCityViewController alloc] init];
        selectCityViewController.isEdit = NO;
        [self.navigationController pushViewController:selectCityViewController animated:YES];
        [selectCityViewController release];
        
        [[DataSource shareInstance] delCurrentEventAll];
        [eventArray removeAllObjects];
        
        NSMutableArray* removeArray = [NSMutableArray array];
        for (int i = 0; i< [eventShowView.subviews count]; i++) {
            id view = [eventShowView.subviews objectAtIndex:i];
            if ([view isKindOfClass:[EventThumbViem class]])
            {
                [removeArray addObject:view];
            }
        }
        for (int i = 0; i < [removeArray count]; i++) {
            id view = [removeArray objectAtIndex:i];
            [view removeFromSuperview];
        }
        [self reloadEventShowView];
    }
    
    if (alertView.tag == 2000) {
        if (buttonIndex == 0) {
            [[DataSource shareInstance] resetData];
        }
        [self.navigationController popViewControllerAnimated:YES];
    }
    
}

- (void)imageButtonTouchUpInside:(NSInteger)index
{
    NSLog(@"the index is %d",index);
    switch (index) {
        case EVENTTYPE_TRAVEL:
        case EVENTTYPE_EAT:
        case EVENTTYPE_LIVE:
        case EVENTTYPE_BUY:
        case EVENTTYPE_PLAY:
        {
            if ([[DataSource shareInstance] getDefaultCityId] == nil) {
                UIAlertView* baseAlert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"还未选择城市哟~" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
                [baseAlert show];
                [baseAlert release];
                return;
            }
            EventViewController* eventViewController = [[EventViewController alloc] initWithType:NO edit:NO];
            eventViewController.elementType = index;
            eventViewController.delegate = self;
            [self.navigationController pushViewController:eventViewController animated:YES];
            [eventViewController release];
        }
            break;
        case 5000:
        {
            if ([[[DataSource shareInstance] getCurrentEvent] count] > 0) {
                UIAlertView* baseAlert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"切换城市会清除所有已经添加的事件。" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确认",nil];
                baseAlert.tag = 1000;
                [baseAlert show];
                [baseAlert release];
                return;
            }
            SelectCityViewController* selectCityViewController = [[SelectCityViewController alloc] init];
            selectCityViewController.isEdit = NO;
            [self.navigationController pushViewController:selectCityViewController animated:YES];
            [selectCityViewController release];
        }
            break;
            
        default:
            break;
    }
}

#pragma mark - addEventDelegate

- (void)delButtonPressed:(PlaceInfo*)info
{
    [self delEvent:info type:1];
}

- (BOOL)addEvent:(PlaceInfo*)info type:(ElementType)type
{
    NSArray* currentArray = [[DataSource shareInstance] getCurrentEvent];
    for (PlaceInfo* place in currentArray) {
        if ([info.shopid isEqualToString:place.shopid]) {
            return NO;
        }
    }
    isChanged = YES;
    info.typeid = [NSString stringWithFormat:@"%d",type];
    [[DataSource shareInstance] setCurrentEvent:info];
    [eventArray addObject:info];
    [self reloadEventShowView];
    return YES;
}

- (BOOL)delEvent:(PlaceInfo*)info type:(ElementType)type
{
    isChanged = YES;
    info.typeid = [NSString stringWithFormat:@"%d",type];
    for (PlaceInfo* placeInfo in eventArray) {
        if ([info.shopid isEqualToString:placeInfo.shopid]) {
            [eventArray removeObject:placeInfo];
            break;
        }
    }
    [[DataSource shareInstance] delCurrentEvent:info];
    
    NSMutableArray* removeArray = [NSMutableArray array];
    for (int i = 0; i< [eventShowView.subviews count]; i++) {
        id view = [eventShowView.subviews objectAtIndex:i];
        if ([view isKindOfClass:[EventThumbViem class]])
        {
            [removeArray addObject:view];
        }
    }
    for (int i = 0; i < [removeArray count]; i++) {
        id view = [removeArray objectAtIndex:i];
        [view removeFromSuperview];
    }
    
    [self reloadEventShowView];
    return YES;
}

@end
